const Koa = require('koa')
const InitManager = require('./core/init')
const path = require('path')
const { resolve } = require('path')
const { koaBody } = require('koa-body')
const cors = require('@koa/cors')
const ratelimit = require('koa-ratelimit')
require('module-alias/register')
const views = require('koa-views')
const koaStatic = require('koa-static')
const catchError = require('./middlewares/exception')

const app = new Koa()

app.use(koaStatic(__dirname + '/public', { alias: '/api/v1/upload' })) // //开启静态资源访问
app.use(
    views(resolve(__dirname, './views'), {
        extension: 'ejs',
    })
)
app.use(cors())
app.use(catchError)
app.use(
    koaBody({
        multipart: true,
        formidable: {
            uploadDir: path.join(__dirname, '/public'), //配置保存路径
            keepExtensions: true, //保存文件扩展名
        },
    })
)

// 接口调用频率限制（Rate-Limiting）
// Rate limiter middleware for koa.
// https://github.com/koajs/ratelimit
const db = new Map()
app.use(
    ratelimit({
        driver: 'memory',
        db: db,
        duration: 60000,
        errorMessage: 'Sometimes You Just Have to Slow Down.',
        id: (ctx) => ctx.ip,
        headers: {
            remaining: 'Rate-Limit-Remaining',
            reset: 'Rate-Limit-Reset',
            total: 'Rate-Limit-Total',
        },
        max: 100,
        disableHeader: false,
        whitelist: (ctx) => {
            // some logic that returns a boolean
        },
        blacklist: (ctx) => {
            // some logic that returns a boolean
        },
    })
)

InitManager.initCore(app)

app.listen(5000, () => {
    console.log('Koa is listening in http://localhost:5000')
})

module.exports = app
